package com.xiaoyu.binaryTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: DS_and_A
 * @description: 翻转一颗二叉树
 *
 * 输入：
 *      4
 *    /   \
 *   2     7
 *  / \   / \
 * 1   3 6   9
 * 输出：
 *      4
 *    /   \
 *   7     2
 *  / \   / \
 * 9   6 3   1
 *
 * @author: YuWenYi
 * @create: 2021-05-19 10:57
 **/
public class InvertTree_226 {
    //层次遍历进行二叉树翻转
    public static TreeNode invertTree(TreeNode root) {
        if (root == null){
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode node = queue.poll();
            //交换左右子树的位置
            TreeNode temp;
            temp = node.left;
            node.left = node.right;
            node.right = temp;
            if (node.left!=null){
                queue.offer(node.left);
            }
            if (node.right!=null){
                queue.offer(node.right);
            }
        }
        return root;
    }

    //使用递归进行翻转
    public static TreeNode invertTree1(TreeNode root) {
        if (root == null){
            return null;
        }
        TreeNode left = invertTree1(root.left);
        TreeNode right = invertTree1(root.right);

        root.right = left;
        root.left = right;

        return root;
    }

    public static void main(String[] args) {
        TreeNode right = new TreeNode(3,new TreeNode(6),new TreeNode(7));
        TreeNode left = new TreeNode(2,new TreeNode(4),new TreeNode(5));
        TreeNode root = new TreeNode(1,left,right);

        TreeNode tree = invertTree1(root);

        LevelOrder_102.simpleLevelOrder(tree);

    }
}
